from threading import Thread
from collections import OrderedDict
from copy import copy, deepcopy

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog, QLabel, QMainWindow,
        QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,
        QVBoxLayout, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,
        QWidget, QRadioButton, QMessageBox, QTableWidget, QTableWidgetItem)

from config import *


LOG = make_logging("winmode")


class KWindow(QWidget):  # QMainWindow
    def __init__(self):
        super().__init__()


class EditWinMode(Thread):
    list_header = ["name", "type", "size", "pos"]
    def __init__(self):
        super().__init__()
        self.win = KWindow()
        self.win.setWindowTitle("编辑模式")
        self.win.resize(800, 600)
        self.active_page = None

    def get_window_obj(self):
        return self.win

    def _install_layout(self):
        vbox = QVBoxLayout()
        lb = QLabel("Here are all the element in this page:", self.win)
        vbox.addWidget(lb)
        self._table_init(vbox)

        hbox = QHBoxLayout()
        dict_btn_func = OrderedDict([
            ("保存信息", self._save_table2page),
            # ("生成XML", self._save_page2xml),
            ("重置", self._table_update),
            ("关闭窗口", self.win.close)
        ])
        for name, func in dict_btn_func.items():
            btn = QPushButton(name, self.win)
            btn.clicked.connect(func)
            hbox.addWidget(btn)
        vbox.addLayout(hbox)

        self.win.setLayout(vbox)

    def _table_init(self, layout):
        dict_header = OrderedDict([
            # ("序号", 50),
            ("名称", 150),
            ("控件类型", 180),
            ("size", 200),
            ("position", 100)
        ])
        column_width = list(dict_header.values())
        n_column = len(column_width)

        self.table = QTableWidget(self.win)
        self.table.setColumnCount(n_column)
        if layout:  layout.addWidget(self.table)
        self.table.resize(800,550)
        self.table.setHorizontalHeaderLabels(dict_header.keys())

        row_header = self.table.verticalHeader()  # 行
        column_header = self.table.horizontalHeader()  # 列
        column_header.setStretchLastSection(True)  # 填满整个表格
        # row_header.setDefaultSectionSize(30)  # 整体行高

        for i in range(n_column):  # 设置列宽
            column_header.resizeSection(i, column_width[i])

        self.table.cellChanged.connect(self._mark_changed_item)

    def _table_update(self):
        n_row = len(self.active_page.dict_elem["widgets"]) + 1
        self.table.setRowCount(n_row)
        dict_elem = copy.deepcopy(self.active_page.dict_elem)
        row = 0
        for dict_widget in dict_elem["widgets"]:
            n_column = self.table.columnCount()
            if False:  # True
                pass   # 此处未实现动态获取表头项并生成对应dict_widget的list_key

            for column in range(n_column):
                value = dict_widget[self.list_header[column]]
                value = switch_namedtuple2str(value)
                self.table.setItem(row, column, QTableWidgetItem(value))
            row += 1
        self.list_changed_items.clear()

    def _save_table2page(self):
        """ 由于表格并不能显示所有信息，故此处只用于修改部分属性 """
        if not hasattr(self, "list_changed_items"):
            return
        for item in self.list_changed_items:
            row, column = item
            value = self.table.item(row, column).text()
            list_widgets = self.active_page.dict_elem["widgets"]
            if value == list_widgets[row][self.list_header[column]]:
                return
            else:
                list_widgets[row][self.list_header[column]] = value
        self.active_page.uninstall_widgets()
        self.active_page.ui.hide()
        self.active_page.run()

    def _mark_changed_item(self, row:int, column:int):
        if not hasattr(self, "list_changed_items"):
            self.list_changed_items = []
        if (row, column) not in self.list_changed_items:
            self.list_changed_items.append((row, column))

    def run(self):
        self._install_layout()

    def update(self, activePage):
        self.active_page = activePage
        self._table_update()
